package com.gupaoedu.mvcframework.v2.servlet02;

import com.gupaoedu.mvcframework.annotation.GPController;
import com.gupaoedu.mvcframework.annotation.GPService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

/**
 * @author 所谓伊人
 * @date 2022/4/30 - 0:27
 * 第二次 2022/5/04 - 2:00 完成将扫描的类初始化
 */
public class GPDispatcherServlet extends HttpServlet {

    // 保存application.properties配置文件的内容
    private Properties contextConfig = new Properties();

    // 享元模式，保存扫描的所有类名
    private List<String> classNames = new ArrayList<String>();

    // IOC容器
    private Map<String, Object> ioc = new HashMap<String, Object>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
    @Override
    public void init(ServletConfig config) throws ServletException {

        // 1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        // 2.扫描相关的类
        doScanner(contextConfig.getProperty("scanPackage"));

        // 3.将扫描到的类初始化，并且将它们放到ioc容器当中=======>使用反射
        doInstance();

        // 4.完成依赖注入
        doAutowired();

        // 5.初始化HandlerMapping
        initHandlerMapping();


        System.out.println("lin Spring framework is init!");
    }

    /**
     * 加载配置文件
     * @param contextConfigLocation 文件名称
     */
    private void doLoadConfig(String contextConfigLocation) {

        System.out.println("==================contextConfigLocation======================="+contextConfigLocation);

        InputStream fis = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            contextConfig.load(fis);
            System.out.println("==================contextConfig======================="+contextConfig.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fis) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 扫描配置文件中相关的类
     * @param scanPackage
     */
    private void doScanner(String scanPackage) {
        URL url = this.getClass().getClassLoader().getResource(scanPackage.replaceAll("\\.", "/"));
        File classPath = new File(url.getFile());
        System.out.println("（猜测是叫demo）文件名：" + classPath.getName());
        // 当成是一个ClassPath文件夹
        for (File file : classPath.listFiles()) {
            if (file.isDirectory()) {
                doScanner(scanPackage + "." + file.getName());
            } else {
                if (!file.getName().endsWith(".class")){continue;} // 不是class文件直接跳过
                // String className = file.getName().replace(".class", ""); 只存类名容易重复，所以要储存全路径名称
                String className = (scanPackage + "." + file.getName().replace(".class", ""));
                classNames.add(className);
            }
        }
    }

    /**
     * 将扫描到的类初始化 为DI做准备
     */
    private void doInstance() {
        if (classNames.isEmpty()){return;}

        for (String className : classNames) {
            try {
                Class<?> clazz = Class.forName(className);

                if (clazz.isAnnotationPresent(GPController.class)) {
                    Object instance = clazz.getDeclaredConstructor().newInstance();
                    //Spring默认首字母小写
                    String beanName = toLowerFirstCase(clazz.getName());
                    ioc.put(beanName,instance);
                }else if (clazz.isAnnotationPresent(GPService.class)) {
                    // 此时有三种情况
                    // 1. 自定义beanName
                    String beanName = clazz.getAnnotation(GPService.class).value();
                    // 2. Spring默认首字母小写
                    if ("".equals(clazz.getName())) {
                        beanName = toLowerFirstCase(clazz.getSimpleName());
                    }

                    Object instance = clazz.getDeclaredConstructor().newInstance();
                    ioc.put(beanName,instance);
                    // 3. 接口 只有一个实现类就默认选择这个实现类 多个实现类就报错
                    for (Class<?> i : clazz.getInterfaces()) {
                        if (ioc.containsKey(i.getName())) {
                            throw new Exception("The“"+i.getName()+"”is exists!!");
                        }
                        // 把接口类型直接当作key
                        ioc.put(i.getName(),instance);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 字符串首字母小写
     * @param name 类名
     * @return
     */
    private String toLowerFirstCase(String name) {
        char[] chars = name.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }

    private void initHandlerMapping() {

    }

    private void doAutowired() {

    }

}
